package com.jr.controller;

import com.google.gson.Gson;
import com.jr.pojo.Users;
import com.jr.service.IEmployeesService;
import com.jr.service.IUsersEmployeesService;
import com.jr.service.IUsersService;
import com.jr.service.impl.EmployeesServiceImpl;
import com.jr.service.impl.UsersEmployeesServiceImpl;
import com.jr.service.impl.UsersServiceImpl;
import com.jr.util.PageHelper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/users/*")
public class UsersController extends HttpServlet {

    IUsersService ius = new UsersServiceImpl();
    IEmployeesService ies = new EmployeesServiceImpl();
    IUsersEmployeesService iues = new UsersEmployeesServiceImpl();

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String requestURI = request.getRequestURI(); // 获取完整请求路径  --- /aaa/projectInfo/showdt
        int index = requestURI.lastIndexOf("/") + 1;
        String mName = requestURI.substring(index); // 截取最后一个"/"之后的字符串作为方法名

        /* 反射获取并调用对应方法 */
        Class cla = this.getClass(); // 获取当前类的Class对象
        Method method = null;
        try {
            // 查找当前类中是否存在指定名称、且参数为HttpServletRequest和HttpServletResponse的方法
            method = cla.getMethod(mName, HttpServletRequest.class, HttpServletResponse.class);

            response.setContentType("application/json;charset=UTF-8");
            request.setCharacterEncoding("UTF-8");

            // 调用找到的方法，this表示当前类实例，传递request和response作为参数
            method.invoke(this, request, response);
        } catch (NoSuchMethodException e) {
            e.printStackTrace(); // 找不到对应方法的处理（这会导致404错误）
        } catch (IllegalAccessException e) {
            e.printStackTrace(); // 方法访问权限不足的处理
        } catch (InvocationTargetException e) {
            e.printStackTrace(); // 方法调用过程中抛出异常的处理
        }
    }


    // 登录时的 密码验证
    public void finduser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String passwordIn = request.getParameter("password");

        boolean boo = false;
        Integer loginedUserId = null;
        Users user = ius.queryUsersByName(username);
        if(user!=null && passwordIn.equals(user.getPassword())){
            boo = true;
            loginedUserId = user.getId();
        }

        Map<String,Object> result = new HashMap<>();
        result.put("successLogin",boo);
        result.put("userId",loginedUserId);

        /*System.out.println("isadmin的值："+user.getRole().equals("管理员")); //true
        System.out.println("user.getRole()的值："+user.getRole()); //管理员*/

        result.put("isadmin", user.getRole().equals("管理员"));

        response.getWriter().println(new Gson().toJson(result));

    }

    // 动态加载数据 + 模糊查询
    public void getListByPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PageHelper ph = new PageHelper();
        /*当前是第几页*/
        int indexpage = Integer.parseInt(request.getParameter("indexpage"));
        String search = request.getParameter("search");
        int i = iues.queryPageDataCountByName(search); // 按名字查询的总条数
        ph.setPageIndex(indexpage);// 当前页
        ph.setDataCount(i); // 分页查询 总条数
        ph.setListIndex(iues.queryIndexDataByName(search,ph)); // 分页查询 查询当前页面 展示集合

//        System.out.println("查询到的集合："+iues.queryIndexDataByName(search,ph));

        /*最终目的：*/
        response.getWriter().println(new Gson().toJson(ph));
    }

    /* 添加用户 */
    public void addUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        Users user = ius.queryUsersByName(username);

        boolean addBoo = false;
        Map<String,Object> result = new HashMap<>();
        result.put("successAddUser",addBoo);

        /* 没写完 */


    }

    /* 删除用户 */
    public void deleteUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String delusername = request.getParameter("delusername");
        Users user = ius.queryUsersByName(delusername);
        Integer userId = user.getId();
        String role = user.getRole();
        boolean delBoo;
        if("管理员".equals(role)){
            delBoo = false;
        }else{
            delBoo = ius.removeUsersByUserName(delusername);
        }
        System.out.println("删除用户Id--userId "+userId+"，删除结果--delBoo："+delBoo);

        Map<String,Object> result = new HashMap<>();
        result.put("successDeleteUser",delBoo);
        result.put("deluserId",userId);
        response.getWriter().println(new Gson().toJson(result));

    }

    /* 个人设置 -- 修改个人设置 */
    public void updateUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        Users user = new Users();
        //添加修改信息

        ius.updateUsers(user);

    }

}
